package com.supcon.exchangedata.service;


import com.supcon.exchangedata.pojo.entity.oracle.StatistOtherParametersDay;
import com.supcon.exchangedata.pojo.entity.oracle.StatistOtherParametersMonth;
import com.supcon.exchangedata.repository.master.MasterStatistOtherParametersDayRepository;
import com.supcon.exchangedata.repository.master.MasterStatistOtherParametersMonthRepository;
import com.supcon.exchangedata.repository.slave1.SlaveOneStatistOtherParametersDayRepository;
import com.supcon.exchangedata.repository.slave1.SlaveOneStatistOtherParametersMonthRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class DayAndMonthSyncService {

    @Resource
    private MasterStatistOtherParametersDayRepository masterDay;
    @Resource
    private MasterStatistOtherParametersMonthRepository masterMonth;
    @Resource
    private SlaveOneStatistOtherParametersMonthRepository slaveOneMonth;
    @Resource
    private SlaveOneStatistOtherParametersDayRepository slaveOneDay;

    @Transactional(rollbackFor = Exception.class)
    public void SyncDayData(Integer officeMonth) {

        LocalDate date = LocalDate.now();
        if (officeMonth != null && officeMonth != 0) {
            date = date.minusMonths(officeMonth);
        }
        //获取当月一号
        LocalDate firstDay = date.with(TemporalAdjusters.firstDayOfMonth());
        LocalDateTime startDateTime = firstDay.atStartOfDay();


        //当月最后一天
        LocalDateTime endTime = LocalDate.now().atStartOfDay();
        //获取当月最后一天
        if (officeMonth != null && officeMonth != 0) {
            LocalDate lastDay = date.with(TemporalAdjusters.lastDayOfMonth()); // 获取当前月的最后一天
            endTime = lastDay.atStartOfDay();
        }
        List<StatistOtherParametersDay> dayList = slaveOneDay.findAllByCondition(startDateTime, endTime);

        int size = dayList.size();


        if (!CollectionUtils.isEmpty(dayList)) {

            if (size > 50) {
                int sizePer = size / 50;
                for (int i = 0; i < 50; i++) {
                    if (i == 49) {
                        List<StatistOtherParametersDay> statistOtherParametersDays = dayList.subList(i * sizePer, dayList.size() - 1);
                        new Thread(() -> {
                            statistOtherParametersDays.forEach((e) -> {
                                LocalDateTime dayOfMonthKey = e.getDayOfMonthKey();
                                Long objId = e.getObjId();
                                Long type = e.getType();
                                StatistOtherParametersDay masterEntity = masterDay.findByObjIdAndTypeAndDayOfMonthKey(objId, type, dayOfMonthKey);
                                if (masterEntity != null) {
                                    //旧版数据库无值
                                    if (masterEntity.getInAvgValue() == null) {
                                        masterEntity.setInAvgValue(e.getInAvgValue());
                                        masterDay.updateDay(e.getInAvgValue(), objId, dayOfMonthKey, type);
                                    }
                                } else {
                                    LocalDateTime lastTime = e.getLastTime();
                                    if (lastTime == null) {
                                        lastTime = e.getDayOfMonthKey();
                                    }
                                    masterDay.insertDay(e.getId(), e.getObjId(), e.getType(), e.getDayOfMonthKey(), e.getInAvgValue(), e.getObjType(), lastTime);
                                }

                            });

                        }).start();
                    } else {
                        List<StatistOtherParametersDay> statistOtherParametersDays = dayList.subList(i * sizePer, (i + 1) * sizePer);
                        new Thread(() -> {
                            statistOtherParametersDays.forEach((e) -> {
                                LocalDateTime dayOfMonthKey = e.getDayOfMonthKey();
                                Long objId = e.getObjId();
                                Long type = e.getType();
                                StatistOtherParametersDay masterEntity = masterDay.findByObjIdAndTypeAndDayOfMonthKey(objId, type, dayOfMonthKey);
                                if (masterEntity != null) {
                                    //旧版数据库无值
                                    if (masterEntity.getInAvgValue() == null) {
                                        masterEntity.setInAvgValue(e.getInAvgValue());
                                        masterDay.updateDay(e.getInAvgValue(), objId, dayOfMonthKey, type);
                                    }
                                } else {
                                    LocalDateTime lastTime = e.getLastTime();
                                    if (lastTime == null) {
                                        lastTime = e.getDayOfMonthKey();
                                    }
                                    masterDay.insertDay(e.getId(), e.getObjId(), e.getType(), e.getDayOfMonthKey(), e.getInAvgValue(), e.getObjType(), lastTime);
                                }

                            });

                        }).start();
                    }


                }
            } else {
                dayList.forEach((e) -> {
                    LocalDateTime dayOfMonthKey = e.getDayOfMonthKey();
                    Long objId = e.getObjId();
                    Long type = e.getType();
                    StatistOtherParametersDay masterEntity = masterDay.findByObjIdAndTypeAndDayOfMonthKey(objId, type, dayOfMonthKey);
                    if (masterEntity != null) {
                        //旧版数据库无值
                        if (masterEntity.getInAvgValue() == null) {
                            masterEntity.setInAvgValue(e.getInAvgValue());
                            masterDay.updateDay(e.getInAvgValue(), objId, dayOfMonthKey, type);
                        }
                    } else {
                        LocalDateTime lastTime = e.getLastTime();
                        if (lastTime == null) {
                            lastTime = e.getDayOfMonthKey();
                        }
                        masterDay.insertDay(e.getId(), e.getObjId(), e.getType(), e.getDayOfMonthKey(), e.getInAvgValue(), e.getObjType(), lastTime);
                    }

                });
            }

        }

    }


    @Transactional(rollbackFor = Exception.class)
    public void SyncCurrentDayData(Integer day) {

        LocalDate date = LocalDate.now();

        //距离今天day天数据
        LocalDateTime startDateTime = date.atStartOfDay().minusDays(day);


        //今日日期
        LocalDateTime endTime = date.atStartOfDay();

        List<StatistOtherParametersDay> dayList = slaveOneDay.findAllByCondition(startDateTime, endTime);

        int size = dayList.size();


        if (!CollectionUtils.isEmpty(dayList)) {

            if (size > 50) {
                int sizePer = size / 50;
                for (int i = 0; i < 50; i++) {
                    if (i == 49) {
                        List<StatistOtherParametersDay> statistOtherParametersDays = dayList.subList(i * sizePer, dayList.size() - 1);
                        new Thread(() -> {
                            statistOtherParametersDays.forEach((e) -> {
                                LocalDateTime dayOfMonthKey = e.getDayOfMonthKey();
                                Long objId = e.getObjId();
                                Long type = e.getType();
                                StatistOtherParametersDay masterEntity = masterDay.findByObjIdAndTypeAndDayOfMonthKey(objId, type, dayOfMonthKey);
                                if (masterEntity != null) {
                                    //旧版数据库无值
                                    if (masterEntity.getInAvgValue() == null) {
                                        masterEntity.setInAvgValue(e.getInAvgValue());
                                        masterDay.updateDay(e.getInAvgValue(), objId, dayOfMonthKey, type);
                                    }
                                } else {
                                    LocalDateTime lastTime = e.getLastTime();
                                    if (lastTime == null) {
                                        lastTime = e.getDayOfMonthKey();
                                    }
                                    masterDay.insertDay(e.getId(), e.getObjId(), e.getType(), e.getDayOfMonthKey(), e.getInAvgValue(), e.getObjType(), lastTime);
                                }

                            });

                        }).start();
                    } else {
                        List<StatistOtherParametersDay> statistOtherParametersDays = dayList.subList(i * sizePer, (i + 1) * sizePer);
                        new Thread(() -> {
                            statistOtherParametersDays.forEach((e) -> {
                                LocalDateTime dayOfMonthKey = e.getDayOfMonthKey();
                                Long objId = e.getObjId();
                                Long type = e.getType();
                                StatistOtherParametersDay masterEntity = masterDay.findByObjIdAndTypeAndDayOfMonthKey(objId, type, dayOfMonthKey);
                                if (masterEntity != null) {
                                    //旧版数据库无值
                                    if (masterEntity.getInAvgValue() == null) {
                                        masterEntity.setInAvgValue(e.getInAvgValue());
                                        masterDay.updateDay(e.getInAvgValue(), objId, dayOfMonthKey, type);
                                    }
                                } else {
                                    LocalDateTime lastTime = e.getLastTime();
                                    if (lastTime == null) {
                                        lastTime = e.getDayOfMonthKey();
                                    }
                                    masterDay.insertDay(e.getId(), e.getObjId(), e.getType(), e.getDayOfMonthKey(), e.getInAvgValue(), e.getObjType(), lastTime);
                                }

                            });

                        }).start();
                    }


                }
            } else {
                dayList.forEach((e) -> {
                    LocalDateTime dayOfMonthKey = e.getDayOfMonthKey();
                    Long objId = e.getObjId();
                    Long type = e.getType();
                    StatistOtherParametersDay masterEntity = masterDay.findByObjIdAndTypeAndDayOfMonthKey(objId, type, dayOfMonthKey);
                    if (masterEntity != null) {
                        //旧版数据库无值
                        if (masterEntity.getInAvgValue() == null) {
                            masterEntity.setInAvgValue(e.getInAvgValue());
                            masterDay.updateDay(e.getInAvgValue(), objId, dayOfMonthKey, type);
                        }
                    } else {
                        LocalDateTime lastTime = e.getLastTime();
                        if (lastTime == null) {
                            lastTime = e.getDayOfMonthKey();
                        }
                        masterDay.insertDay(e.getId(), e.getObjId(), e.getType(), e.getDayOfMonthKey(), e.getInAvgValue(), e.getObjType(), lastTime);
                    }

                });
            }

        }

    }


    @Transactional(rollbackFor = Exception.class)
    public void SyncAppointDayData(Integer day, Map<Long,Long> indexParam) {

        LocalDate date = LocalDate.now();

        //距离今天day天数据
        LocalDateTime startDateTime = date.atStartOfDay().minusDays(day);


        //今日日期
        LocalDateTime endTime = date.atStartOfDay();
        List<StatistOtherParametersDay> dayList = new ArrayList<>();

        indexParam.forEach((k,v)->{
            List<StatistOtherParametersDay> result = slaveOneDay.findAllByObjIdAndTypeAndInAvgValueIsNotNullAndDayOfMonthKeyBetween(v, k, startDateTime, endTime);
            dayList.addAll(result);
        });


        int size = dayList.size();


        if (!CollectionUtils.isEmpty(dayList)) {

            if (size > 50) {
                int sizePer = size / 50;
                for (int i = 0; i < 50; i++) {
                    if (i == 49) {
                        List<StatistOtherParametersDay> statistOtherParametersDays = dayList.subList(i * sizePer, dayList.size() - 1);
                        new Thread(() -> {
                            statistOtherParametersDays.forEach((e) -> {
                                LocalDateTime dayOfMonthKey = e.getDayOfMonthKey();
                                Long objId = e.getObjId();
                                Long type = e.getType();
                                StatistOtherParametersDay masterEntity = masterDay.findByObjIdAndTypeAndDayOfMonthKey(objId, type, dayOfMonthKey);
                                if (masterEntity != null) {
                                    //旧版数据库无值
                                    if (masterEntity.getInAvgValue() == null) {
                                        masterEntity.setInAvgValue(e.getInAvgValue());
                                        masterDay.updateDay(e.getInAvgValue(), objId, dayOfMonthKey, type);
                                    }
                                } else {
                                    LocalDateTime lastTime = e.getLastTime();
                                    if (lastTime == null) {
                                        lastTime = e.getDayOfMonthKey();
                                    }
                                    masterDay.insertDay(e.getId(), e.getObjId(), e.getType(), e.getDayOfMonthKey(), e.getInAvgValue(), e.getObjType(), lastTime);
                                }

                            });

                        }).start();
                    } else {
                        List<StatistOtherParametersDay> statistOtherParametersDays = dayList.subList(i * sizePer, (i + 1) * sizePer);
                        new Thread(() -> {
                            statistOtherParametersDays.forEach((e) -> {
                                LocalDateTime dayOfMonthKey = e.getDayOfMonthKey();
                                Long objId = e.getObjId();
                                Long type = e.getType();
                                StatistOtherParametersDay masterEntity = masterDay.findByObjIdAndTypeAndDayOfMonthKey(objId, type, dayOfMonthKey);
                                if (masterEntity != null) {
                                    //旧版数据库无值
                                    if (masterEntity.getInAvgValue() == null) {
                                        masterEntity.setInAvgValue(e.getInAvgValue());
                                        masterDay.updateDay(e.getInAvgValue(), objId, dayOfMonthKey, type);
                                    }
                                } else {
                                    LocalDateTime lastTime = e.getLastTime();
                                    if (lastTime == null) {
                                        lastTime = e.getDayOfMonthKey();
                                    }
                                    masterDay.insertDay(e.getId(), e.getObjId(), e.getType(), e.getDayOfMonthKey(), e.getInAvgValue(), e.getObjType(), lastTime);
                                }

                            });

                        }).start();
                    }


                }
            } else {
                dayList.forEach((e) -> {
                    LocalDateTime dayOfMonthKey = e.getDayOfMonthKey();
                    Long objId = e.getObjId();
                    Long type = e.getType();
                    StatistOtherParametersDay masterEntity = masterDay.findByObjIdAndTypeAndDayOfMonthKey(objId, type, dayOfMonthKey);
                    if (masterEntity != null) {
                        //旧版数据库无值
                        if (masterEntity.getInAvgValue() == null) {
                            masterEntity.setInAvgValue(e.getInAvgValue());
                            masterDay.updateDay(e.getInAvgValue(), objId, dayOfMonthKey, type);
                        }
                    } else {
                        LocalDateTime lastTime = e.getLastTime();
                        if (lastTime == null) {
                            lastTime = e.getDayOfMonthKey();
                        }
                        masterDay.insertDay(e.getId(), e.getObjId(), e.getType(), e.getDayOfMonthKey(), e.getInAvgValue(), e.getObjType(), lastTime);
                    }

                });
            }

        }

    }

    @Transactional(rollbackFor = Exception.class)
    public void SyncMonthData(Integer officeMonth) {
        Integer errorCode = 0;

        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate now = LocalDate.now().minusMonths(officeMonth);
        String monthKey = dateTimeFormatter.format(now);
        monthKey = monthKey.substring(0, 7);
        List<StatistOtherParametersMonth> monthList = slaveOneMonth.findAllByCondition(monthKey);
        if (!CollectionUtils.isEmpty(monthList)) {
            for (StatistOtherParametersMonth e : monthList) {
                Long objId = e.getObjId();
                Long type = e.getType();
                String monthKey1 = e.getMonthKey();

                if (e.getInAvgValue() == null || StringUtils.isEmpty(monthKey1) || objId == null || type == null) {
                    continue;
                }


                StatistOtherParametersMonth targetMonthData = masterMonth.findByObjIdAndTypeAndMonthKey(objId, type, monthKey1);
                if (targetMonthData != null) {
                    if (targetMonthData.getInAvgValue() == null) {
                        masterMonth.updateMonth(e.getInAvgValue(), objId, monthKey1, type);
                    }
                } else {
                    LocalDateTime lastTime = e.getLastTime();
                    if (lastTime == null) {
                        lastTime = now.atStartOfDay();
                    }

                    try {
                        masterMonth.insertMonth(e.getId(), e.getObjId(), e.getType(), e.getMonthKey(), e.getInAvgValue(), e.getObjType(), lastTime);
                    } catch (Exception ex) {
                        log.info("错误信息:{},{},{},{},{},{},{}", e.getId(), e.getObjId(), e.getType(), e.getMonthKey(), e.getInAvgValue(), e.getObjType(), lastTime);
                        errorCode++;
                    }
                }
            }

        }
        log.info("导入错误数量:" + errorCode);

    }
}
